package cc.xpcas.raft.component;

import java.util.*;
import java.util.function.*;

/**
 * @author xp
 */
public class MultiIteratorMixer<T> implements Iterator<T> {

    private final Iterator<T>[] iterators;

    private int i = 0;

    private T nextValue;

    @SafeVarargs
    public MultiIteratorMixer(Iterator<T>... iterators) {
        this.iterators = iterators;
    }

    @Override
    public boolean hasNext() {
        if (nextValue != null) return true;
        while (i < iterators.length) {
            if (iterators[i].hasNext()) {
                nextValue = iterators[i].next();
                return true;
            }
            i++;
        }
        return false;
    }

    @Override
    public T next() {
        try {
            return nextValue;
        } finally {
            nextValue = null;
        }
    }

    public MultiIteratorMixer<T> skip(int length) {
        for (int i = length; i > 0 && hasNext(); --i) {
            next();
        }
        return this;
    }

    public MultiIteratorMixer<T> skipUntil(Predicate<T> predicate) {
        while (hasNext()) {
            if (predicate.test(nextValue)) break;
            next();
        }
        return this;
    }
}
